import hashlib

import requests
from lxml import html

loginUrl = 'http://chandao.tpson.com.cn/zentao/user-login.html'
password = 'linzhou123456'
loginName = 'linzhou'

#获取禅道session
def getSession():
    loginPage = requests.get(loginUrl)
    loginPage.encoding = 'utf-8'
    SID = loginPage.cookies['zentaosid']
    # print('SID = ' + SID)
    loginTree = html.fromstring(loginPage.text)
    verifyRand = loginTree.xpath('//*[@id="verifyRand"]')
    if verifyRand:
        verifyRand = verifyRand[0].attrib['value']
    # print('verifyRand = ' + verifyRand)
    hl = hashlib.md5()
    hl.update(password.encode(encoding='utf-8'))
    # print('Md5 第一次加密结果 = ' + hl.hexdigest())
    passwordResult = hl.hexdigest() + verifyRand
    # print("passwordResult=" + passwordResult)
    hlLast = hashlib.md5()
    hlLast.update(passwordResult.encode(encoding='utf-8'))
    # print('Md5 第二次加密结果 = ' + hlLast.hexdigest())
    loginBody = {"account": loginName, "password": hlLast.hexdigest(), "keepLogin[]": "on"}
    loginCookies = dict(zentaosid=SID, lang='zh-cn', keepLogin='on')
    session=requests.session()
    conteent=session.post(loginUrl, data=loginBody, cookies=loginCookies)
    loginResultPage = requests.post(loginUrl, data=loginBody, cookies=loginCookies)
    # print('loginResultPage = ' + loginResultPage.text)
    # token = loginResultPage.cookies['zp']
    # print('token = ' + token)
    return session
if __name__ == '__main__':
    session=getSession()
    print(session)

